package com.youthburin.rmp.services.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.youthburin.rmp.domain.RmpPermission;
import com.youthburin.rmp.domain.RmpRole;
import com.youthburin.rmp.domain.RmpUser;
import com.youthburin.rmp.domain.UserInfo;
import com.youthburin.rmp.services.UserInfoService;

@Service
@Transactional
public class UserInfoServiceImpl implements UserInfoService {
	@PersistenceContext
	private EntityManager em;

	@Override
	public Map<String, Set<String>> getRoleAndPermission(String userCode) {
		RmpUser user = em.find(RmpUser.class, userCode);
		Set<String> roles = new HashSet<String>();
		Set<String> permissions = new HashSet<String>();
		if (user != null) {
			Set<RmpRole> roleSet = user.getRmpRoles();
			if (roleSet != null && !roleSet.isEmpty()) {
				for (RmpRole role : roleSet) {
					roles.add(role.getCode());
					if (role.getRmpPermissions() != null && !role.getRmpPermissions().isEmpty()) {
						for (RmpPermission permission : role.getRmpPermissions()) {
							permissions.add(permission.getCode());
						}
					}
				}
			}
		}
		Map<String, Set<String>> roleAndPermission = new HashMap<String, Set<String>>();
		roleAndPermission.put("roles", roles);
		roleAndPermission.put("permissions", permissions);

		return roleAndPermission;
	}

	@Override
	public UserInfo getSystemUserInfo(String userCode) {
		RmpUser user = em.find(RmpUser.class, userCode);

		UserInfo userInfo = new UserInfo();
		try {
			BeanUtils.copyProperties(userInfo, user);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return userInfo;
	}

	@Override
	public String getPassword(String userCode) {
		RmpUser user = em.find(RmpUser.class, userCode);
		return user!=null?user.getPassword():null;
	}

}
